const _function = require("../../utils/functionData.js")
Page({
  data: {
    chatData: {},
    chatId: null,
    messages: [], // 消息列表
    inputValue: '', // 输入框内容
    lastMsgId: 0, // 最后一条消息的ID，用于滚动到底部
    url: 'ws://127.0.0.1:8080/websocket/1/student'  // WebSocket服务器地址
  },

  onLoad: function (options) {
    // console.log("接收到的 Item:", options);
    const item = JSON.parse(decodeURIComponent(options.data));
    console.log("接收到的 Item:", item);
    // 模拟初始消息
    this.setData({
      // chatId: id,
      chatData: item,
      chatId: item.id,
      socketMsgQueue:[],
      // messages: [
      //   { id: 1, avatar: 'https://img.yzcdn.cn/vant/cat.jpeg', content: '你好！', isMe: false },
      //   { id: 2, avatar: 'https://img.yzcdn.cn/vant/cat.jpeg', content: '你好，有什么可以帮你的？', isMe: true },

      // ],
      lastMsgId: 2,
      role: getApp().globalData.userInfo.role
    });
    this.createSocketServer();
    this.getRecordList();
  },

  createSocketServer: function () {
    var that = this
    wx.connectSocket({
      url: that.data.url,
      success: function (res) {
        console.log('WebSocket连接成功')
      },
      fail: function (res) {
        console.log('WebSocket连接失败:', res)
      }
    })
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开')
      that.setData({
        socketOpen: true
      })
      for (var i = 0; i < that.data.socketMsgQueue.length; i++) {
        that.sendSocketMessage(that.data.socketMsgQueue[i])
      }
      that.setData({
        socketMsgQueue: []
      })
    })
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败:', res)
    })
    wx.onSocketClose(function (res) {
      console.log('WebSocket连接已关闭:', res)
      that.setData({
        socketOpen: false
      })
    })
    wx.onSocketMessage(function (res) {
      console.log('接收到服务器发送的数据:', res.data)
      that.getRecordList()
      // var messages = that.data.messages
      // messages.push(res.data)
      // that.setData({
      //   messages: messages,
      //   scrollIntoView: 'message-' + messages.length
      // })
    })
  },
  getRecordList() {
    console.log('获取聊天列表');
    const prams = {
      chatId: this.data.chatId,
      speak_user: getApp().globalData.userInfo.role
    }
    _function.getRecordList(prams, this.getRecordListBack, this)
  },
  getRecordListBack(res) {
    let dataAll = res.data
    if (dataAll.code == 200) {
      this.setData({
        messages: dataAll.rows.reverse()
      })
      console.log('消息列表',dataAll.rows);
    }
  },
  /**
   * 发送消息
   */
  sendMessage: function () {

    // if (!this.data.socketOpen) {
    //   wx.showToast({
    //     title: 'WebSocket未连接',
    //     icon: 'none'
    //   })
    //   return
    // }
    const message = this.data.inputValue
    if (message == '') {
      wx.showToast({
        title: '消息不能为空',
        icon: 'none'
      })
      return
    }
    // this.sendSocketMessage(message)

    // 处理确认逻辑
    console.log('this.chatData.studentId',this.data.chatData);
    const param = {
      chatId: this.data.chatId,
      senderId: getApp().globalData.userInfo.userId,
      speakUser: getApp().globalData.userInfo.role,
      receiverId: getApp().globalData.userInfo.role == 0 ? this.data.chatData.studentId : this.data.chatData.teacherId,
      content: message
    }
    console.log('参数', param);
    _function.postSendMessage(param, this.postSendMessageBack, this)
  },

  postSendMessageBack(res) {
    let that = this
    let dataAll = res.data
    if (dataAll.code == 200) {
      console.log('视频列表', dataAll);
      // this.setData({
      //   reservations: dataAll.rows
      // })
      that.getRecordList()
      this.setData({
        inputValue: ''
      })
      wx.showToast({
        title: dataAll.msg,
        icon: 'none', // 不显示图标
        duration: 1500, // 提示的延迟时间，单位毫秒，默认为 1500
        mask: true, // 是否显示透明蒙层，防止触摸穿透，默认为 `false`
        success: () => {
          // console.log('登录失败提示已显示');
        }
      });
    }
  },

  /**
   * 发送WebSocket消息
   */
  // sendSocketMessage: function (message) {
  //   if (this.data.socketOpen) {
  //     wx.sendSocketMessage({
  //       data: message
  //     })
  //   } else {
  //     this.data.socketMsgQueue.push(message)
  //   }
  // },
  // 输入框内容变化
  onInput: function (event) {
    this.setData({
      inputValue: event.detail.value
    });
  },

  // // 发送消息
  // sendMessage: function () {
  //   const content = this.data.inputValue.trim();
  //   if (!content) return;

  //   const newMessage = {
  //     id: this.data.lastMsgId + 1,
  //     avatar: 'https://img.yzcdn.cn/vant/cat.jpeg', // 用户头像
  //     content: content,
  //     isMe: true
  //   };

  //   this.setData({
  //     messages: [...this.data.messages, newMessage],
  //     inputValue: '',
  //     lastMsgId: newMessage.id
  //   });
  //   // 请求订单列表

  //   // 模拟对方回复
  //   setTimeout(() => {
  //     const replyMessage = {
  //       id: this.data.lastMsgId + 1,
  //       avatar: 'https://img.yzcdn.cn/vant/cat.jpeg', // 对方头像
  //       content: '收到你的消息了！',
  //       isMe: false
  //     };

  //     this.setData({
  //       messages: [...this.data.messages, replyMessage],
  //       lastMsgId: replyMessage.id
  //     });
  //   }, 1000);
  //   _function.getHotJob(this.data.param, this.getHotJobBack, this)
  // },

  getHotJobBack(res) {
    let dataAll = res.data
    if (dataAll.code == 200) {
      this.setData({
        jobList: dataAll.data
      })
    }
  },
});